package com.pig4cloud.pig.ads.datasource;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

//数据源2
//@Configuration
//配置mybatis的接口类放的地方
//@MapperScan(basePackages = "com.pig4cloud.pig.ads.clickhouse.mapper", sqlSessionFactoryRef = "clickSqlSessionFactory")
public class ClickDataSourceConfig {
	
//	@Autowired
	private PaginationInterceptor paginationInterceptor;
	
	// 将这个对象放入Spring容器中
//	@Bean(name = "clickDataSource")
//	@ConfigurationProperties(prefix = "spring.datasource.click")
	public DataSource getDateSource2() {
		return DataSourceBuilder.create().build();
	}

//	@Bean(name = "clickSqlSessionFactory")
	// 表示这个数据源是默认数据源
	// @Qualifier表示查找对象
	public MybatisSqlSessionFactoryBean cstSqlSessionFactory(@Qualifier("clickDataSource") DataSource datasource) throws Exception {
		MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(getDateSource2());
		//这里如果用mybatis plus的话，要用mybatis-plus的configuration
		MybatisConfiguration configuration = new MybatisConfiguration(); 
		//configuration.setMapUnderscoreToCamelCase(false); 
		sqlSessionFactoryBean.setConfiguration(configuration);
	    sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/click/**/*.xml"));
	    
	    //设置 MyBatis-Plus 分页插件
		Interceptor[] plugins = {paginationInterceptor};
		sqlSessionFactoryBean.setPlugins(plugins);
		return sqlSessionFactoryBean;
	}

//	@Bean("clickSqlSessionTemplate")
	public SqlSessionTemplate test1sqlsessiontemplate(
			@Qualifier("clickSqlSessionFactory") SqlSessionFactory sessionfactory) {
		return new SqlSessionTemplate(sessionfactory);
	}
}